import 'dart:async';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import '../common/api_service.dart';
import '../common/constants.dart';
import '../common/events.dart';
import '../common/routes.dart';
import '../model/user_model.dart';
import '../service/auth_service.dart';
import '../widgets/dialog.dart';
import '../widgets/mine_cartoon_list_view.dart';
import '../widgets/mine_pipe_list_view.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> with SingleTickerProviderStateMixin {
  StreamSubscription? _loginStreamSub;
  late TabController _tabController;
  UserModel? _user;
  String? _userAvatarFrame;
  final String _uid = "8XMOY9HZH";

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _getUserInfo();
    _loginStreamSub = eventBus.on<UserLoggedInEvent>().listen((event) {
      _getUserInfo();
    });
  }

  @override
  void dispose() {
    _loginStreamSub?.cancel();
    _tabController.dispose();
    super.dispose();
  }

  void _getUserInfo() {
    ApiService().getUserInfo(_uid, (user) {
      setState(() {
        _user = user;
        _userAvatarFrame = _user?.setting?.avatarFrame;
      });
    }, () {});
  }

  void _showLogoutDialog(VoidCallback callback) {
    HDialog.showCustom(
        title: "当前账号为游客账号",
        content: "退出当前账号可能会导致用户信息丢失，确定退出吗？",
        confirmTitle: "确认退出",
        cancelTitle: "绑定手机号",
        confirmAction: () {
          eventBus.fire(UserLogoutEvent());
          final authService = Get.find<AuthService>();
          authService.logout();
          callback();
        },
        cancelAction: () {
          callback();
        });
  }

  _buildSettingItem(IconData icon, String title, VoidCallback onTap) {
    return InkWell(
      onTap: () {
        onTap();
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        height: 36,
        child: Row(
          children: [
            Icon(icon, color: Colors.black54, size: 18),
            const SizedBox(width: 5),
            Text(title, style: const TextStyle(fontSize: 16, color: Colors.black54)),
            const Spacer(),
            const Icon(Icons.chevron_right, color: Colors.black26, size: 18),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: _user == null
          ? const SizedBox.shrink()
          : NestedScrollView(
              headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverAppBar(
                    systemOverlayStyle: const SystemUiOverlayStyle(statusBarBrightness: Brightness.light, statusBarIconBrightness: Brightness.light),
                    toolbarHeight: 0,
                    pinned: true,
                    expandedHeight: 260.0,
                    flexibleSpace: FlexibleSpaceBar(
                      collapseMode: CollapseMode.pin,
                      background: _user == null
                          ? null
                          : Stack(
                              children: [
                                CachedNetworkImage(
                                  width: double.infinity,
                                  fadeInDuration: const Duration(seconds: 0),
                                  fadeOutDuration: const Duration(seconds: 0),
                                  fit: BoxFit.cover,
                                  imageUrl: _user?.avatar ?? "",
                                  errorWidget: (_, url, object) {
                                    return Container(color: Colors.grey[200]);
                                  },
                                ),
                                BackdropFilter(
                                  filter: ImageFilter.blur(sigmaX: 15.0, sigmaY: 15.0),
                                  child: Container(
                                    color: Colors.black.withAlpha(127),
                                  ),
                                ),
                                Container(
                                  padding: const EdgeInsets.only(top: 90),
                                  child: Column(children: [
                                    GestureDetector(
                                      onTap: () {
                                        Get.toNamed(Routes.ACCOUNT_SETTINGS);
                                      },
                                      child: Stack(
                                        children: [
                                          ClipRRect(
                                            borderRadius: BorderRadius.circular(36),
                                            child: CachedNetworkImage(
                                              height: 72,
                                              width: 72,
                                              fadeInDuration: const Duration(seconds: 0),
                                              fadeOutDuration: const Duration(seconds: 0),
                                              fit: BoxFit.cover,
                                              imageUrl: _user?.avatar ?? "",
                                              errorWidget: (_, url, object) {
                                                return Container(color: Colors.grey[200]);
                                              },
                                            ),
                                          ),
                                          if (_userAvatarFrame != null && _userAvatarFrame!.isNotEmpty)
                                            Positioned(
                                                left: -9,
                                                top: -9,
                                                child: CachedNetworkImage(
                                                  height: 90,
                                                  width: 90,
                                                  imageUrl: _userAvatarFrame ?? "",
                                                ))
                                        ],
                                      ),
                                    ),
                                    const SizedBox(height: 10),
                                    Text(
                                      _user?.nickname ?? "",
                                      style: const TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
                                    ),
                                    const SizedBox(height: 4),
                                    GestureDetector(
                                      onTap: () async {
                                        await Clipboard.setData(ClipboardData(text: _user?.uid ?? ""));
                                        Fluttertoast.showToast(msg: "ID 已复制", gravity: ToastGravity.CENTER);
                                      },
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            "ID: ${_user?.uid ?? ""}",
                                            style: const TextStyle(fontSize: 13, color: Colors.white54),
                                          ),
                                          const SizedBox(width: 3),
                                          const Icon(Icons.copy, size: 12, color: Colors.white54)
                                        ],
                                      ),
                                    )
                                  ]),
                                ),
                                Positioned(
                                  right: 10,
                                  top: 50,
                                  child: GestureDetector(
                                    child: Container(
                                      margin: const EdgeInsets.only(right: 10),
                                      decoration: const BoxDecoration(
                                        shape: BoxShape.circle,
                                        color: Colors.white60,
                                      ),
                                      padding: const EdgeInsets.all(5.0),
                                      child: const Icon(Icons.more_horiz, size: 20),
                                    ),
                                    onTap: () {
                                      // _showSettingsView();
                                      Scaffold.of(context).openEndDrawer();
                                    },
                                  ),
                                )
                              ],
                            ),
                    ),
                    bottom: PreferredSize(
                      preferredSize: Size(MediaQuery.of(context).size.width, 44.0),
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(16),
                            topRight: Radius.circular(16),
                          ),
                        ),
                        height: 44,
                        child: TabBar(
                          dividerHeight: 0,
                          labelColor: Constants.themeColor,
                          labelStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                          unselectedLabelColor: Colors.grey,
                          unselectedLabelStyle: const TextStyle(fontSize: 15),
                          indicatorColor: Constants.themeColor,
                          controller: _tabController,
                          tabs: const [
                            Tab(text: '内容'),
                            Tab(text: '角色'),
                          ],
                        ),
                      ),
                    ),
                  ),
                ];
              },
              body: TabBarView(
                controller: _tabController,
                children: [MinePipeListView(uid: _uid), MineCartoonListView(uid: _uid)],
              ),
            ),
      endDrawer: Drawer(
        width: 250,
        backgroundColor: Colors.white,
        child: ListView(
          padding: const EdgeInsets.all(0),
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: Text(_user?.nickname ?? ""),
              accountEmail: Text(_user?.uid ?? ""),
              currentAccountPicture: ClipRRect(
                borderRadius: BorderRadius.circular(36),
                child: CachedNetworkImage(
                  height: 72,
                  width: 72,
                  fadeInDuration: const Duration(seconds: 0),
                  fadeOutDuration: const Duration(seconds: 0),
                  fit: BoxFit.cover,
                  imageUrl: _user?.avatar ?? "",
                  errorWidget: (_, url, object) {
                    return Container(color: Colors.grey[200]);
                  },
                ),
              ),
              decoration: BoxDecoration(color: Constants.themeColor),
            ),
            const SizedBox(height: 10),
            _buildSettingItem(Icons.edit, "账号设置", () {
              Get.back();
              Get.toNamed(Routes.ACCOUNT_SETTINGS);
            }),
            _buildSettingItem(Icons.payments, "充值中心", () {
              Get.back();
              Get.toNamed(Routes.RECHARGE);
            }),
            _buildSettingItem(Icons.assignment, "隐私政策", () {}),
            _buildSettingItem(Icons.gavel, "用户协议", () {}),
            _buildSettingItem(Icons.info_outline, "关于FlowGPT", () {}),
            _buildSettingItem(Icons.logout, "退出登录", () {
              Get.back();
              _showLogoutDialog(() {});
            })
          ],
        ),
      ),
    );
  }
}
